/* getMcard--获取车牌月卡信息
 * getPaylist---// 获取生成订单的信息
 * */
/*初始化*/
;$(function(){
	cardData.exitSn = getParam("ex");
	cardData.lotSn = getParam("lotSn");
	getCarPlates();/*车牌列表*/
	getCarType();//获取车牌的月卡资料
});
var _config = {
		timeout: 16000,
	};
var cardData={
      exitSn:'',//出口sn
      lotSn:'',//车场sn
	  carPlateId:'',//车牌id
      vehicleType:'',//汽车类型id
      number:"",// 缴费月数id
      carPlate:"",
      carType:'',//汽车类型文本
      mNumber:'',
      plateList:[],//汽车类型表
      parkingInfo:{}
  };
var layer_loading;
const getParam=(param)=>{
    var reg = new RegExp('(^|&)' + param + '=([^&]*)(&|$)', 'i');
    var r = window.location.search.substr(1).match(reg);
    if (r != null) {
    return unescape(r[2]);
    }
    return null;
};
//确认选择--提示弹窗
 const layTip=(message,el,t)=>{
    layer.tips(message,el, {
      tips: [1, '#78BA32'],
      time: t
    });
 };
 const getTime=(end)=>{
	 var now= new Date();
	 var year=now.getFullYear();
	 var month=now.getMonth()+1;
	 var day=now.getDate();
	 var hour=now.getHours();
	 var minute=now.getMinutes();
	 var second=now.getSeconds();
	 if(end){
		  month=parseInt(end)+parseInt(month);
		 if(month>12){
			 year= parseInt(year)+1;
			 month=month-12;
		 }
	    if (month >= 1 && month <= 9) {
	        month = "0" + month;
	    }
	    if (second >= 0 && second <= 9) {
	    	second = "0" + second;
	    }	    
		 return year+"-"+month+"-"+day+" "+hour+":"+minute+":"+second
	 }else{
		    if (month >= 1 && month <= 9) {
		        month = "0" + month;
		    }
		    if (second >= 0 && second <= 9) {
		    	second = "0" + second;
		    }		    
		 return year+"-"+month+"-"+day+" "+hour+":"+minute+":"+second
	 }
 };
 /**预创建缴费订单: */
 const getPaylist=(data)=>{
    $.ajax({
      url:"/member/mcard/createorder",
      type:"post",
      timeout: _config.timeout,
      contentType:"application/json",      
      data:JSON.stringify(data),
      beforeSend: function(){
			layer_loading=layer.msg('查询订单信息中，请稍等。。。', {
				  icon: 16
				  ,shade: 0.01
				  ,time: 0
			});		
      },      
      success:function(res){
    	  layer.close(layer_loading);
    	  if(res.status==0){
    		  layer.alert(res.err, {icon: 4});
 // 预缴费订单信息获取成功，  
    		 
    		  var data=res.datas;
    		  cardData.parkingInfo.lotOrderNo=data.lotOrderNo;//返回的订单编号
    		  let plateNumber=data.carPlate,//车牌号
    		  	  cardNo=data.cardNo,//卡编号
    		  	  cardId=data.cardId,//卡id
    		  	  preExpireTime=data.preExpireTime,//到期时间
    		  	  monthNum=data.monthNum,//缴费月数
    		  	  monthlyRent=data.monthlyRent;//月租  
    //显示订单列表回填资料；    		  
    		  $('.mark').addClass('show-mark');//显示订单    		  
              $('.mark .plateNumber').find('.content').text(plateNumber);
              $('.mark .vehicleType').find('.content').text(cardData.carType);//汽车类型
              $('.mark .cardTime').find('.content').text(monthNum);
              $('.mark .cardNo').find('.content').text(cardNo);
              $('.mark .endTime').find('.content').text(preExpireTime); 
              $('.mark .payMoney .content').find('.money').text(monthlyRent);  		      		  
    		  
    	  }else{
    		  layer.alert(res.err, {icon: 5});
    	  }       
      },
      error:function(res){
    	  layer.alert(res.err, {icon: 4});
      },
	    complete:function(XHR,TextStatus){
	        if(TextStatus=='timeout'){ //超时执行的程序
	            layer.alert("请求超时！", {icon: 5});
	        }
	    }
    })
 };		
/*查询当前月卡信息*/     
const getMonthInfo=(data,callback)=>{
	    $.ajax({
	      url:"/member/mcard/getinfo",
	      type:"post",
	      contentType:"application/json",
	      data:JSON.stringify(data),
	      beforeSend: function(){
			layer_loading=layer.msg('正在获取当前车牌信息中请稍等', {
				  icon: 16
				  ,shade: 0.01
				  ,time: 0
			});		
	      },	      
	      success:function(res){
	    	  layer.close(layer_loading);	    	
	    	  callback(res);	
	      },
	      error:function(res){
	    	  layer.alert(res.err, {icon: 4});
	      }
	    })
};
/*查询月卡*/
	function getMcard(res){
	    if(res.status==0){
	    	var data=res.datas;
	    	var $vehicleType=$('.card-select .vehicleType');//车类型区块
	    	if(data.isSuccess){
	    		//当前车牌有月卡
	    		cardData.vehicleType=data.tariffId;//把车型id存在cardData中
	    		/*显示到期时间*/
	    		$('.card-select .vehicleType').addClass("active");
	    		$('.vehicleType .tip .endtime').text(data.currExpiryDate);
    			var carType=cardData.plateList,//车类型表
    				self_tariffId=data.tariffId;//当前车类型的id	
//假设的车型id==》因为当前接口id不匹配   			
    			carType.forEach(function(currentValue, index, arr){
					  if(currentValue.tariffId==self_tariffId){
				//获取原有的车型，然后进行显示								  
						  $vehicleType.find(".select").hide();
						  $vehicleType.find(".content").show();
						  $vehicleType.find(".content").text(currentValue.tariffName);
						  cardData.carType=currentValue.tariffName;
					  }				  
    			});	    		
	    		if(data.monthCardExpired){
	    			//月卡过期=》提示月卡过期
	    			layer.alert('抱歉您的月卡已经到期', {icon: 4});

	    		}else{
	    			//月卡没有过期==》显示到期时间  			
	    		}
	    	}else{
	    		//当前车牌没有月卡
				  $vehicleType.find(".select").show();
				  $vehicleType.find(".content").hide();
				  $('.card-select .vehicleType').removeClass("active");
	    	}
	    }else{
	    	///返回数据报错
	    	layer.alert(res.err, {icon: 4});
	    }	
	};
	/*查询缴费结果*/
	function chargeResult(res){
		console.log(res)
	};
/*车类型*/
 const getCarType=(data)=>{
	 var loading=layer.load();
	 $.ajax({
		 url:"/member/mcard/chargeoptions",
		 type:"post",
		 contentType:"application/json",
	     success:function(result){
	    	 layer.close(loading);
	    	  if(result.status==0){
	    		  let data=result.datas;
	    		  cardData.plateList=data;//存起来
	    		  var carList="";
	    		  data.forEach(function(currentValue, index, arr){
	    			  carList+="<li data-id='"+currentValue.tariffId+"'>"+currentValue.tariffName+"</li>";					
	    		  });		    		 
	    		  $('#select_vehicleType').html(carList);
	    	  }
	     }
	 })		 
 };
 /*车牌列表*/
const getCarPlates = ()=>{
	var loading=layer.load();
	 //查询当前车牌又没有月卡--！	
	$.ajax({
		url:'/member/mcard/getinfos',
		type:'post',
		success:function(result){
			layer.close(loading);
			 var carPlateList="";
	    	  if(result.status==0){
	    		  let data=result.datas;
	    		  data.forEach(function(currentValue, index, arr){
	    			  carPlateList+="<li data-mcard='"+currentValue.isSuccess+"' data-id='"+currentValue.carPlateId+"'>"+currentValue.carPlate+"</li>";					
	    		  });		    		 
	    		  $('#select_plateNumber').html(carPlateList);
	    	  }				
		}
	})
};
function payType(){
	var browser = navigator.userAgent.toLowerCase();
	if(browser.match(/Alipay/i)=="alipay"){
		return "Alipay";   
	}else if(browser.match(/MicroMessenger/i)=="micromessenger"){
		return "weixin";    
	}else{
		return false;	
	}		
};
/*支付-----*/
/*下单*/
function createOrder() {
	layer_loading=layer.msg('支付中。。。', {
		  icon: 16
		  ,shade: 0.01
		  ,time: 0
		});			
	var loading = true;
	var data = {
		lotOrderNo: cardData.parkingInfo.lotOrderNo,
		carPlateId: cardData.carPlateId,//车牌id
		money: cardData.parkingInfo.fee,//支付金额
		lotSn: cardData.lotSn,//车场sn
		remark: ''
	};
	$.ajax({
		url : '/member/order/create',
		method : "POST",
		data : JSON.stringify(data),
		dataType : "json",
		contentType : "application/json;charset=UTF-8",
		success : function(result) {
			if (cardData.parkingInfo.fee == 0) {
				if (result.status == "0") {
					location.href = "/member/advert/get";
				} else {
					loading?(layer.close(layer_loading),loading = false):false;
					layer.alert(result.err, {icon: 5});
				}
			} else {
				if (result.status == 0) {
					if (payType() === "weixin") {
						onWeixinPay(result.datas);
					} else {
						onAlipay(result.datas);
					}
				} else {
					loading?(layer.close(layer_loading),loading = false):false;
					layer.alert(result.err, {icon: 5});
				}
			}

		},
		error: function(error) {
			loading?(layer.close(layer_loading),loading = false):false;
			layer.alert('网络连接失败', {icon: 5});
		},
		complete: function(){
			loading?(layer.close(layer_loading),loading = false):false;
		}
	})
}
//微信
function onWeixinPay(data) {
	if (typeof WeixinJSBridge == "undefined") {
		if (document.addEventListener ) {
			document.addEventListener('WeixinJSBridgeReady', function(){weixinpay(data)}, false);
		} else if (document.attachEvent) {
			document.attachEvent('WeixinJSBridgeReady', function(){weixinpay(data)});
			document.attachEvent('onWeixinJSBridgeReady', function(){weixinpay(data)});
		}
	} else {
		weixinpay(data);
	}
}
function weixinpay(data){
	WeixinJSBridge.invoke("getBrandWCPayRequest", {
		appId : data.appId, //公众号名称，由商户传入
		timeStamp : data.timeStamp, //时间戳，自1970年以来的秒数
		nonceStr : data.nonceStr, //随机串
		package : data.packages,
		signType : data.signType, //微信签名方式：
		paySign : data.paySign
	//微信签名
	}, function(res) {
		if (res.err_msg == "get_brand_wcpay_request:ok") {
			//支付成功的同步
			location.href = "/member/advert/get?orderSn="+data.orderNo;
		} else if (res.err_msg == "get_brand_wcpay_request:cancel") {
			layer.alert('取消支付', {icon: 6});
        } else if (res.err_msg == "get_brand_wcpay_request:fail") {
        	layer.alert('支付失败', {icon: 5});
        }
	});
}
//支付宝
function onAlipay(data) {
	AlipayJSBridge.call("tradePay", {
		tradeNO : data.pre_trade_no
	}, function(result) {
		if (result.resultCode == "9000") {
			//支付成功
			location.href = "/member/advert/get?orderSn="+data.orderNo;
		} else if (result.resultCode == "8000") {
			//正在处理
			layer_loading=layer.msg('查询停车费用', {
				  icon: 16
				  ,shade: 0.01
				  ,time: 1500
				});					
		} else if (result.resultCode == "4000") {
			//订单失败
			layer.msg('订单失败', {icon: 5});
		} else if (result.resultCode == "6001") {
			//中途取消
			layer.msg('支付失败', {icon: 5});
		} else if (result.resultCode == "6002") {
			//网络错误
			layer.msg('网络异常，请重试', {icon: 5});
		}
	});
};
//点击确认信息
    $('.confirm').click(function(){    
    	/*        把月卡信息放在cardData里面*/
      if(!cardData.carPlateId){
          return layTip("请选择车牌",".card-select .plateNumber","1500")
      };
      if(!cardData.vehicleType){
          return layTip("请选择车类型",".card-select .vehicleType","1500")
      };
      if(!cardData.number){
          return layTip("请选择充值月数",".card-select .cardTime","1500")
      };            
      if(cardData.carPlateId&&cardData.vehicleType&&cardData.number){             
              //根据车型查charge
				var carType=cardData.plateList;//车类型表
				var charge=0;//初始化的金额
				carType.forEach(function(currentValue, index, arr){
				 if(currentValue.tariffId==cardData.vehicleType){
						  //匹配车型查取金额	
					 charge=currentValue.charge
				 }					  
				}); 
			cardData.parkingInfo.fee=charge;//缴费金额 */ 
             let userData={
            		  money:charge,
            		  lotSn:cardData.lotSn,
            		  monthNum:cardData.number,
            		  carPlateId:cardData.carPlateId,
            		  tariffId:cardData.vehicleType,
            		  remark:'',
            		  lotOrderSn:""
              };        
  //预下单    
              getPaylist(userData);
      };
        
    });
/*菜单事件*/
    $('.card-select .select').click(function(){
    	var index=$(this).parent('.inpbox').index();
    	$('.plate-select').find('ul').eq(index).show().siblings('ul').hide();
    	$('.plate-select').addClass('show-plate');
    });
//选择菜单内容--回填，记录信息
    $('.plate-select').on("click","li",function(){
    	let index=$(this).parent('ul').index();//判断选择类型==0，车牌，1，车型；2=》月数；
    	var id=$(this).attr("data-id"),
    		text=$(this).text();
    	if(index==0){
    		let hasCard=$(this).attr("data-mcard");//有没有办过月卡
    		if(hasCard){
    			 /*车牌查询月卡 信息  */ 
    			getMonthInfo({"carPlateId":id},getMcard);
    		}else{
    			
    		}    		
    		cardData.carPlateId=id;
    		cardData.carPlate=text;
    		$('.card-select .select').eq(0).html(text);
    	}else if(index==1){
    		cardData.vehicleType=id;
    		cardData.carType=text;
    		$('.card-select .select').eq(1).html(text);
    	}else{    		
    		cardData.number=id;
    		cardData.mNumber=text;
    		$(this).addClass('active').siblings("li").removeClass('active');//选中标记==》月数
    		$('.card-select .select').eq(2).html(text);
    	}   	
  	
    });   
//关闭遮罩！
    $('.plate-select').click(function(){
        $(this).removeClass('show-plate');
    });   
//支付
    $('.submit').click(function(){    
    	createOrder();
    });
    $('.mark').click(function(){
      $(this).removeClass('show-mark');
    }); 
    $('.order-header .close').click(function(){
       $('.mark').removeClass('show-mark');
    });       
    $('.dialog').click(function(event){
       event.stopPropagation();
       //阻止事件捕获
    });